package com.zone.gateway.assist.domain.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zone.gateway.assist.config.ApiGatewayProperties;
import com.zone.gateway.assist.domain.model.aggregate.ApplicationGatewayRichInfo;
import com.zone.gateway.common.response.Result;
import com.zone.gateway.common.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/4/24
 */
public class GatewayCenterService {
    private Logger logger = LoggerFactory.getLogger(GatewayCenterService.class);


    public void register(ApiGatewayProperties properties) {
        Map<String, Object> params = new HashMap<>();
        params.put("groupId", properties.getGroupId());
        params.put("gatewayId", properties.getGatewayId());
        params.put("gatewayName", properties.getGatewayName());
        params.put("gatewayAddress", properties.getGatewayAddress());
        String resultStr = HttpUtil.createPost(properties.getRegisterUrl() + "/gateway/config/manage/regis")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonPrettyStr(params))
                .execute()
                .body();
        logger.info("gateway to register center gatewayName = {} result = {}", properties.getGatewayName(), resultStr);
    }

    public ApplicationGatewayRichInfo queryApplicationRichInfo(String gatewayId, String centerUrl) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("gatewayId", gatewayId);

        String result = HttpUtil.get(centerUrl + "/gateway/config/manage/query_application_rich_info", paramMap);
        return JSONObject.parseObject(result, ApplicationGatewayRichInfo.class);
    }

    public List<String> queryGatewayIds(String centerUrl, String systemId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("systemId", systemId);

        String resultStr = HttpUtil.get(centerUrl + "/gateway/config/manage/query_gateway_ids", paramMap);
        Result result = JSONObject.parseObject(resultStr, Result.class);
        if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
            logger.warn("queryGatewayIds error systemId: {}", systemId);
            return new ArrayList<>();
        }
        Result<List<String>> resultResponse = JSON.parseObject(resultStr, new TypeReference<Result<List<String>>>() {
        });
        return resultResponse.getData();
    }
}
